﻿using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImmutableCollectionsLab
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> list = new List<string>();
            ImmutableList<string> imList = ImmutableList<string>.Empty;
            var imListBuilder = imList.ToBuilder();
            List<Task> tasks = new List<Task>();
            for (int i = 0; i < 100; i++)
            {

                Task task = Task.Factory.StartNew(index =>
            {
                imListBuilder.Add(index.ToString());// 
                imList = imList.Add(index.ToString());
                Console.WriteLine("{0}: {1} items", index, imListBuilder.Count);

                list.Add(index.ToString());
                //Console.WriteLine("{0}: {1} items", index, list.Count);
            }, i);
                //task.ContinueWith(t =>
                //{
                //    if (t.Exception != null)
                //    {
                //        Console.WriteLine(t.Exception);
                //    }
                //    else
                //    {
                //        if (t.IsCanceled)
                //        {
                //            Console.WriteLine(t.Status.ToString());
                //        }
                //    }
                //});
                tasks.Add(task);
            }
            try
            {
                Task.WaitAll(tasks.ToArray());
            }
            catch (AggregateException ex)
            {
                ex.Handle((innerEx) =>
                {
                    Console.WriteLine(innerEx);
                    return true;
                });
            }
            imList = imListBuilder.ToImmutable();
            Console.WriteLine(imListBuilder.Count);
            Console.WriteLine(list.Count);
            //Console.WriteLine(list.Count);
            //Console.WriteLine("press any key to exit");
            //Console.ReadLine();
        }
    }
}
